package com.internship.javawebinternship.controller;

import com.alibaba.fastjson.JSONObject;
import com.internship.javawebinternship.repository.AccountRepository;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;

@RestController
public class DownloadExcelController {

    @Autowired
    private AccountRepository accountRepository;
    AccountController accountController = new AccountController();

    @GetMapping("/downloadExampleExcel")
    public String downloadFile(HttpServletRequest request,
                               HttpServletResponse response) {

        if (forceLogOut(request)) {
            return "您的账号已在其他地方登录，您已被强制下线。若需要继续操作，请重新登录并注意账号安全";
        }
        HttpSession session = request.getSession(false);

        try {
            if (!session.getAttribute("authority").equals("0")) {
                return "很抱歉，您无权限进行本操作，请联系管理员以获得帮助";
            }
        } catch (NullPointerException e) {
            return "您似乎尚未登录，请登录后重试";
        }
        String fileName = "";
        String realPath = "";
        File file = null;
        if (session.getAttribute("excelPath") == null) {
            fileName = "example.xlsx";
            realPath = "excelUploaded/";
            file = new File(realPath, fileName);
        } else {
            fileName = session.getAttribute("date") + " Excel Exported.xls";
            realPath = "excelGenerated/";
            file = new File(realPath, fileName);
        }
        if (file.exists()) {
            response.setContentType("application/octet-stream");//
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("success");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    public boolean forceLogOut(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        boolean status;
        try {
            if (session == null) {
                status = false;
                return status;
            }
            if (!session.getId().equals(accountRepository.findByStuempno((String) session.getAttribute("no")).get(0).getSessionid())) {
                status = true;
                session.invalidate();
            } else {
                status = false;
            }
        } catch (Exception e) {
            status = true;
            session.invalidate();
            return status;
        }
        return status;
    }
}
